﻿using CommonLib.Util;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SqlConvertTool.DBContext;
using System;
using System.ComponentModel.DataAnnotations;

namespace SqlConvertTool;

public partial class ConnectModel : ObservableValidator
{
    [ObservableProperty]
    [Required]
    private string server;

    [ObservableProperty]
    [Required]
    private string username;

    [ObservableProperty]
    [Required]
    private string password;

    [ObservableProperty]
    [Required]
    private string host;

    public string DBKind { get; set; }

    public string Title { get; }

    public string Name { get; }

    [ObservableProperty]
    private bool hasData;

    [ObservableProperty]
    private bool hasStore;

    public BaseDBContext? DBContext { get; set; }

    public ConnectModel(string dBKind)
    {
        DBKind = dBKind;
        Server = string.Empty;
        Username = string.Empty;
        Password = string.Empty;
        Host = string.Empty;
        HasData = false;
        HasStore = false;
        Title = $"{dBKind} Connect";
        if (DBKind.Equals("Oracle")) Name = "ServerName : ";
        else Name = "DBName : ";
    }

    [RelayCommand]
    public void TestConnect()
    {
        ValidateAllProperties();
        if (HasErrors) return;
        var type = Type.GetType($"SqlConvertTool.DBContext.{DBKind}DBContext");
        DBContext = Activator.CreateInstance(type!) as BaseDBContext;
        var msg = DBContext!.TestConnection(Host, Server, Username, Password);
        if (string.IsNullOrEmpty(msg))
        {
            ConstUtil.DataBase = Username;
            InfoUtil.Success("Connection Success!");
        }
        else InfoUtil.Error(msg);
    }

    [RelayCommand]
    public void Clear()
    {
        Server = string.Empty;
        Username = string.Empty;
        Password = string.Empty;
        Host = string.Empty;
        HasData = false;
        HasStore = false;
    }
}
